import { useRef, useEffect } from "react";
import { useDrop, useDrag } from "react-dnd";
import { getComponentById, useComponentsStore } from "../../stores/components";
import { useComponentConfigStore } from "../../stores/component-config";

import { type CommonComponentProps } from "../Page/dev";

export interface ItemType {
    type: string
    dragType?: 'move' | 'add',
    id?: number
}

const Container = ({ children, id, styles, name }: CommonComponentProps) => {
    const divRef = useRef<HTMLDivElement | null>(null);
    const { addComponent, components, deleteComponent } = useComponentsStore();
    const { componentConfig } = useComponentConfigStore();
    const [{ canDrop }, drop] = useDrop(() => ({
        accept: ['Button', 'Container', 'Input', 'Modal', 'Table', 'Form'],
        drop: (item: ItemType, monitor) => {
            const didDrop = monitor.didDrop();
            if (didDrop) return;
            if (item.dragType === 'move') {
                const component = getComponentById(item.id!, components)!;
                deleteComponent(item.id!)
                addComponent(component, id)
            } else {
                const config = componentConfig[item.type];
                addComponent({
                    id: new Date().getTime(),
                    name: item.type,
                    props: config.defaultProps,
                    desc: config.desc,
                    styles: {
                        backgroundColor: 'green'
                    }
                }, id)
            }
        },
        collect: (monitor) => ({
            canDrop: monitor.canDrop()
        }),
    }))
    const [_, drag] = useDrag({
        type: name,
        item: {
            type: name,
            dragType: 'move',
            id
        }
    })

    useEffect(() => {
        drag(divRef);
        drop(divRef);
    }, [])

    return (
        <div ref={divRef} data-component-id={id} className={`min-h-[100px] p-[20px] ${canDrop ? 'border-[2px] border-[blue]' : 'border-[1px] border-[#000]'}`} style={styles}>
            {children}
        </div>
    )
}

export default Container;